package com.xuzz.study.springbootdemo.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class BaseController {
    public HashMap getUploadFiles(HttpServletRequest request)
    {
        /**
         * 使用Apache Commons FileUpload组件上传文件时总是返回null，调试发现ServletFileUpload对象为空，在Spring Boot中有默认的文件上传组件，在使用ServletFileUpload时需要关闭Spring Boot的默认配置 ，
         *
         * 禁用MultipartResolverSpring提供的默认值
         *
         * 1.0在配置文件中添加
         *
         * spring.http.multipart.enabled=false
         * 2.0在配置文件中添加
         *
         * spring.servlet.multipart.enabled=false
         */
        HashMap requestParams = new HashMap<>();
        try {
            List<FileItem> items = (new ServletFileUpload(new DiskFileItemFactory())).parseRequest(request);
            List fileList = new ArrayList();
            if(null!=items)
            {
                for(FileItem item:items)
                {
                    if(item.isFormField())
                    {
                        requestParams.put(item.getFieldName(),item.getString("UTF-8"));
                    }
                    else
                    {
                        fileList.add(item);
                    }
                }
            }
            if(fileList.size()>0) {
                requestParams.put("uploaded_filelist", fileList);
            }
        }
        catch (Exception var8) {
            var8.printStackTrace();
        }
        return requestParams;
    }

    public HashMap getParamMap(HttpServletRequest request) {
        Map<String, String[]> pm = request.getParameterMap();
        HashMap hm = new HashMap();
        Iterator var4 = pm.keySet().iterator();

        while(var4.hasNext()) {
            String key = (String)var4.next();
            hm.put(key, request.getParameter(key).toString());
        }

        return hm;
    }
}
